package com.zhouzhou.fastjava.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;

public abstract class SpringWebConfig implements WebConfigMXBean, InitializingBean, DisposableBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(SpringWebConfig.class);

    public abstract void onInit();

    public abstract void onDestroy();

    private String mbeanObjectName;

    @Override
    public void afterPropertiesSet() {
        try {
            this.onInit();
        } finally {
            MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
            try {
                mbeanObjectName = this.getClass().getName() + ":type=WebConfig";
                ObjectName name = new ObjectName(mbeanObjectName);
                if (!mbeanServer.isRegistered(name)) {
                    mbeanServer.registerMBean(this, name);
                }
            } catch (Exception e) {
                LOGGER.error("Unable to start/stop JMX", e);
            }
        }
    }

    @Override
    public void destroy() {
        try {
            this.onDestroy();
        } finally {
            MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
            try {
                ObjectName name = new ObjectName(mbeanObjectName);
                if (mbeanServer.isRegistered(name)) {
                    mbeanServer.unregisterMBean(name);
                }
            } catch (Exception e) {
                LOGGER.error("Unable to start/stop JMX", e);
            }
        }
    }

}
